import { Component, OnInit,ViewChild, Injector, Output, EventEmitter, Input, ElementRef } from '@angular/core';
import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../public/serve/init/init.service';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from '../../../public/common/api';
import { tokenName } from '@angular/compiler';
import { DatePipe } from '@angular/common';
import { internal } from '../../internal.data';
import { ActivatedRoute, Params } from '@angular/router';
import { LeftKeywordComponent } from '../left-keyword/left-keyword.component';
import {keyword} from '../../../keyword/keyword.data';

declare var $: any;
@Component({
  selector: 'app-reference-indexing',
  templateUrl: './reference-indexing.component.html',
  styleUrls: ['./reference-indexing.component.css']
})
export class ReferenceIndexingComponent implements OnInit {

  currentRefTabIndex = 1;
  public currentRefTaskThemeTableList : any;
  pageNo :number = 1;
  limitCount = 3;
  pageSize      : number = 20;
  total      : number = 0;
  naturalNum : number = 0;
  public referenceInternalThemeWordsTablesRelEmit: any;
  public referenceInternalThemeWordsLeftEmit: any;
  public referenceThemeInternalAttributeEmit: any;
  @Input() internalParam: any;
  @Input() idxRefTaskThemeTableList: any; //相关主题词表列表
  currentThemeWordInfo:any;
  themeId: number = 0;
  loading: boolean = false;
  taskTabVal: any;
  taskType: any;
  initId: any;
  themeList: any = [];
  themeTableId: any;
  productId: any;
  taskId: any;
  productType: any;
  initIndex = 0;
  treeData: any;
  fileFormat:any = '';
  internalTablesParam = {
    taskId: "",
    productId: "",
    themeTableId: "",
    themeTableName: "",
    themeGroupId: "",
    id: "",
};

  internalContent = '  <h3>第五章</h3>\n' +
    '                      <p> <span title="兄弟">兄弟<<a href="2">兄弟2</a></span>鸿渐想叫辆汽车上轮船码头。精明干练的鹏图说，汽车价钱新近长了好几倍，鸿渐行李简单，又不勿忙，不如叫两辆洋车，反正有凤仪相送。二十二日下午近五点，兄弟俩出门，车拉到法租界边上，有一个法国巡捕领了两个安南巡捕在搜检行人，只有汽车容易通过。鸿渐一瞧那法国巡捕，就是去年跟自己同船来上海的，在船上讲过几次话，他也似乎还认识鸿渐，一挥手，放鸿渐车子过去。鸿渐想同船那批法国警察，都是乡下人初出门，没一个不寒窘可怜。曾几何时，适才看见的一个已经着色*放大了。本来苍白的脸色*现在红得像生牛肉，两眼里新织满红丝，肚子肥凸得像青蛙在鼓气，法国人在国际上的绰号是“虾蟆”，真正名副其实，可惊的是添了一团凶横的兽相。上海这地方比得上希腊神话里的魔女岛，好好一个人来了就会变成畜生。至于那安南巡捕更可笑了。东方民族没有像安南人地样形状委琐不配穿制服的。日本人只是腿太短，不宜挂指挥刀。安南人鸠形鹄面，皮焦齿黑，天生的鸦片鬼相，手里的警棍，更像一支鸦片槍。鸿渐这些思想，安南巡仿佛全猜到，他拦住落后的凤仪那辆车子，报复地搜检个不了。他把饼干匣子，肉松罐头全划破了，还偷偷伸手要了三块钱，终算铺盖袋保持完整。鸿渐管着大小两个箱子，路上不便回头，到码头下车，找不见凤仪，倒发了好一会的急。</p>\n' +
    '                      <p> 鸿渐辛楣是同舱，孙小姐也碰见了，只找不着李顾两人。船开了还不见他们踪迹，辛楣急得满头大汗，鸿渐孙小姐也帮着他慌。正在烦恼茶房跑来说，三等舱有位客人要跟辛楣谈话，不能上头等舱来，只可以请辛楣下去。鸿渐跟辛楣去一看，就是顾先生，手舞足蹈地叫他们下来。两人忙问：“李先生呢？”顾先生道：“他和我同舱，在洗脸。李先生的朋友只买到三张大菜间，所以李先生和我全让给你们，改坐房舱。”两人听了，很过意不去。顾先生道：“房舱也够舒服了，我领两位去参观参观。”两人跟他进舱，满舱是行李，李先生在洗脚。辛楣和鸿渐为舱位的事，向郑重道谢。顾先生插口道：“本来只有两张大菜间，李先生再三恳求他那位朋友，总算弄到第三张。”辛楣道：“其实那两张，你们两位老先生一人一张，我们年轻人应当苦一点。”李先生道：“大不了十二个钟点的事，算不得什么。大菜间我也坐过，并不比房舱舒服多少。”</p>\n' +
    '                  ';

  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
    private datePipe: DatePipe,
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
    private hostElement: ElementRef,
  ) { }

  @ViewChild("leftKeyword") leftKeyword : LeftKeywordComponent;
  ngOnInit() {
    this.activatedRoute.queryParams.subscribe((p: Params) => {
      this.taskType = p['taskType'];
    });

    if(this.taskType == 2){
      this.referenceInternalThemeWordsLeftEmit = this.server.referenceInternalThemeWordsLeftEmit.subscribe((value: any) => {
        if (value) {
          this.currentThemeWordInfo = value
        }
      });
  
      this.referenceInternalThemeWordsTablesRelEmit = this.server.referenceInternalThemeWordsTablesRelEmit.subscribe((value: any) => {
        this._getThemeList();
      });

      this.referenceThemeInternalAttributeEmit = this.server.referenceThemeInternalAttributeEmit.subscribe((value: any) => {
        if (value) {
          this.themeId = value.themeWordsId;
          this.getReferenceProductIndexingMetaList();
        }
      });
    }
  }

  ngOnDestroy() {
    this.referenceInternalThemeWordsLeftEmit ? this.referenceInternalThemeWordsLeftEmit.unsubscribe() : '';
    this.referenceInternalThemeWordsTablesRelEmit ? this.referenceInternalThemeWordsTablesRelEmit.unsubscribe() : '';
    this.referenceThemeInternalAttributeEmit ? this.referenceThemeInternalAttributeEmit.unsubscribe() : '';
  }

  //查询当前任务的参考内容
  _getTaskReferenceContentList() {
      this.win_hide_show(1);
      this.currentRefTaskThemeTableList = this.idxRefTaskThemeTableList;
      //默认显示5个
      if(this.currentRefTaskThemeTableList && this.currentRefTaskThemeTableList.length > 0){
          for(let i =   0;i< this.currentRefTaskThemeTableList.length;i++){
              this.currentRefTaskThemeTableList[i]['active'] = 0;
              if(i < this.limitCount){
                if(i == 0){
                    this.currentRefTaskThemeTableList[i]['active'] = 1;
                }
                this.currentRefTaskThemeTableList[i]['canshow'] = 1;
              }else{
                  this.currentRefTaskThemeTableList[i]['canshow'] = 0;
              }
          }
      }

    if(this.currentRefTaskThemeTableList && this.currentRefTaskThemeTableList.length > 0){
      this.themeTableId = this.currentRefTaskThemeTableList[0].themeTableId;
      let params = this.getTaskProductListParams();
      this.request.postRequest(this.server.baseUrl + 'Service/innertext/getRefIndexingList', params).then((res: any) => {
        if (res.result_code === '0000') {
          this.taskTabVal = res.data;
          if (this.taskTabVal && this.taskTabVal.length > 0) {
            this.initId = this.taskTabVal[0].id; //这个需要改成主键的id
            this.productId = this.taskTabVal[0].productId;
            this.internalTablesParam.productId = this.taskTabVal[0].productId;
            this.taskId = this.taskTabVal[0].taskId;
            //默认显示第一个产品的内容
            this._getShowContent();
          }
  
        } else {
          this.hintsService.messages(res.message, res.result_code);
        }
  
        return;
      });
    }
  }

  //查询参数
  private getTaskProductListParams() {
    return {
      token: internal.retrieval.token,
      taskId: this.internalParam.taskId,
    }
  }


  //点击选中参考内容
  _getChangeShowContent() {
    this.internalContent = '';
    let index = $("#referenceIndexingId").val();
    this.initIndex = index;
    this.productId = this.taskTabVal[this.initIndex].productId;
    this.taskId = this.taskTabVal[this.initIndex].taskId;
    this._getShowContent();
    this._getThemeList();
    this.getReferenceProductIndexingMetaList();
    this.getReferenceProductTimeMetaList();
  }


  //显示产品的内容
  _getShowContent() {
    if (this.taskTabVal && this.taskTabVal.length > 0) {
      let url = this.server.baseUrl + 'Service/IdxProduct/getIndexingDetails';
      let data = {
        "token": "b25dbd7138cf48e09941087e6d9a2e93",
        "id": this.taskTabVal[this.initIndex].id,
      };
      this.request.postRequest(url, data).then((res: any) => {
        if (res.result_code === '0000') {
          if (res.result) {
            if(this.taskType == 2) {
              //主题词标引内容列表
              this.internalTablesParam.productId = this.productId;
              this.leftKeyword._infoThemeTab(this.productId);
            }else if(this.taskType == 1){
              //内文内容
              if(res.result.idxProductInnertext){
                this.internalContent = res.result.idxProductInnertext.fileContent;
              }
            }else if(this.taskType == 0){
              //产品返回的是路径this.taskType == 0，内文返回的是内容this.taskType == 1
              setTimeout(() => {
                if(res.result.idxProducts){
                  this.fileFormat = res.result.idxProducts.fileFormat;//资源类型
                  if(this.fileFormat == 'mp3'){
                      setTimeout(()=>{
                          $("#reference-audio-model").attr("src", res.result.idxProducts.filePath);
                      },100)
                  }else if(this.fileFormat == 'mp4'){
                      setTimeout(()=>{
                        $("#reference-video-model").attr("src", res.result.idxProducts.filePath);
                      },100)
                  }else{
                    $("#iframeReference").attr('src', res.result.idxProducts.filePath);
                  }
                }
                
              }, 100);
            }

            this._getThemeList();
          }
        }
        return;
      })
        .catch((err: any) => {
          this.hintsService._operationHints("error", "error");
          return;
        });
    }
  }

  //查询相关主题词
  _getThemeList() {
    if (this.taskTabVal && this.taskTabVal.length > 0) {
      this.themeList = [];
      let data:any;
      let url:any;
      if(this.taskType == 2){
        data = {
          token: keyword.retrieval.token,
          pageNo        : 1,
          pageSize      : 999,
          queryCriteria : keyword.retrieval.queryCriteria,
          themeTableId  :  this.currentThemeWordInfo['themeTableId'], // 左侧主题词表id
          refThemeTableId  :  this.themeTableId, // 当前主题词表id
          themeWordsId  :  this.currentThemeWordInfo['themeWordsId'],    //左侧主题词id
          productId  : this.productId,
          taskId  : this.taskId
        };
        url = this.server.baseUrl +  'Service/IdxProduct/getProductThemeRelationList';
      }else{
        data = {
          token: keyword.retrieval.token,
          themeTableId: this.themeTableId,
          productId: this.productId,
          taskId: this.taskId,
          pageNo: 1,
          pageSize: 9999,
        };
        url = this.server.baseUrl +  'Service/IdxProduct/getProductThemeWordsList';
      }
      this.request.postRequest(url, data).then((res: any) => {
        if (res.result_code === '0000') {
          this.themeList = res.result;
          this.total = res.length;
          this.naturalNum = internal.pagination.naturalNum;
         
        } else {
          this.hintsService.messages(res.message, res.result_code);
        }
        this.loading = false;
        return;
      })
      .catch((err: any) => {
        this.hintsService.messages("error", "error");
        return;
      });
    }
  }

  /**
   * 分页
   * @param pagination 
   */ 
  _pagination(pagination: Array<any>) {
    this.pageNo = pagination[0].pageNumber;
    this.pageSize   = pagination[0].pageSize;
    this.naturalNum = (this.pageNo - 1) * this.pageSize;
    this._getThemeList();
  }

  /**
   * 获取主题词的完整路径名称（2）
   */
  _getThemeName(list, arrparentid) {
    let tname = '';
    if (list.length > 0) {
      if (arrparentid != 0) {
        let arrId = arrparentid.split(",");
        if (arrId) {
          list.forEach(item => {
            arrId.forEach(tid => {
              if (Number(tid) === Number(item['themeWordsId'])) {
                if (item['name']) {
                  tname += item['name'] + '\\';
                }
              }
            });
          });
        }
      }
    }
    return tname;
  }

  //切换主题词表
  changeRefThemeTable(themeTableId) {
    this.win_hide_show(2);
    this.themeTableId = themeTableId;
      for(let i = 0;i< this.currentRefTaskThemeTableList.length;i++){
          this.currentRefTaskThemeTableList[i]['active'] = 0;
          if(this.currentRefTaskThemeTableList[i].themeTableId == themeTableId){
              this.currentRefTaskThemeTableList[i]['active'] = 1;
          }
      }
    this._getThemeList();
  }

  //参考标引的上一篇
  _refereceIndexingPrevious() {
    if(this.taskTabVal && this.taskTabVal.length > 0){
      if (this.taskTabVal.length != (Number(this.initIndex) - 1) && this.initIndex != 0) {
        this.initIndex = Number(this.initIndex) - 1;
  
        this.productId = this.taskTabVal[this.initIndex].productId;
        this.taskId = this.taskTabVal[this.initIndex].taskId;
  
        this._getShowContent();
        this._getThemeList();
      } else {
        this.hintsService.messages('已经是第一篇了！', '0000');
      }
    }
    
  }

  //参考标引的下一篇
  _refereceIndexingNext() {
    if(this.taskTabVal && this.taskTabVal.length > 0){
      if (this.taskTabVal.length != (Number(this.initIndex) + 1) && (this.taskTabVal.length != this.initIndex)) {
        this.initIndex = Number(this.initIndex) + 1;
        this.productId = this.taskTabVal[this.initIndex].productId;
        this.taskId = this.taskTabVal[this.initIndex].taskId;
  
        this._getShowContent();
        this._getThemeList();
      } else {
        this.hintsService.messages('已经是最后一篇了！', '0000');
      }
    }
    
  }

  _moveTab(type){
      if(type == 'plus'){
          if(this.currentRefTaskThemeTableList && this.currentRefTaskThemeTableList.length > this.limitCount){
              if((this.currentRefTaskThemeTableList.length - this.currentRefTabIndex) >= this.limitCount){
                  this.currentRefTabIndex++;
              }
          }
      }else{
        if(this.currentRefTabIndex > 1){
            this.currentRefTabIndex--;
        }
      }

      for(let i = 0;i< this.currentRefTaskThemeTableList.length;i++){
          this.currentRefTaskThemeTableList[i]['canshow'] = 0;
      }

      if(this.currentRefTaskThemeTableList && this.currentRefTaskThemeTableList.length > 0){
          let n = 0;
          for(let i = (this.currentRefTabIndex - 1);i< this.currentRefTaskThemeTableList.length;i++){
              n++;
              if(n <= this.limitCount){
                  this.currentRefTaskThemeTableList[i]['canshow'] = 1;
              }else{
                  this.currentRefTaskThemeTableList[i]['canshow'] = 0;
              }
          }
      }
  }
    _leftShift() {
        var zuo = $('#myWinTxtTab li').css("left");
        var kuandu = $("#myWinTxtTab li").width()+8;
        var zuo02 = parseInt(zuo) + kuandu;
        if(parseInt(zuo) < 0){
            if(parseInt(zuo) <= 0 && parseInt(zuo) >= -106){
                $("#myWinTxtTab li").animate({left:'0px'});
            }else{
                $("#myWinTxtTab li").animate({left:zuo02 + 'px'});
            }

        }
    }

    _rightShift() {
        var zuo = $('#myWinTxtTab li').css("left");
        var you = $('#myWinTxtTab li').css("right");
        var kuandu = $("#myWinTxtTab li").width()+8;
        var zuo02 = parseInt(zuo) - kuandu;
        var p = kuandu * $("#myWinTxtTab li").length;
        if(parseInt(you) < p/2 && p>$("#myWinTxtTab").width()){
            $("#myWinTxtTab li").animate({left:zuo02 + 'px'});
        }
    }

     //切换到时间属性
     public winTimeAttr = false;
     _winChangTimeAttribute(){
       if(!this.winTimeAttr){
        $('#myWinTxtTab li a').attr('class','');
        $("#Wintab11").hide();
        $("#Wintab22").hide();
        $("#Wintab33").show();
        this.winTimeAttr = true;
        this.winAttr = false;
        this.getReferenceProductTimeMetaList();
       }
     }

     /**
     * 查询时间属性列表
     */
    winTimeTabVal : Array<object>;
    public getReferenceProductTimeMetaList(){
      let url = this.server.baseUrl + 'Service/IdxProduct/getProductTimeMetaList';
      let data = this._tableDataTime();
      this.request.postRequest(url,data).then((res:any) => {
          if (res.result_code === '0000') {
              this.winTimeTabVal = res.result; 
          }
          return;
      })
      .catch((err: any)=>{
          return;
      });
    }

  //查询参数
  private _tableDataTime(){
    return {
      token         : internal.retrieval.token,
      pageNo        : 1,
      pageSize      : 200,
      productId     : this.productId
    }
  }

 
     //切换到属性
     public winAttr = false;
     _winChangAttribute(){
       if(!this.winAttr){
        $('#myWinTxtTab li a').attr('class','');
        $("#Wintab11").hide();
        $("#Wintab22").show();
        $("#Wintab33").hide();
        this.winAttr = true;
        this.winTimeAttr = false;
        this.getReferenceProductIndexingMetaList();
       }
     }

     /**
     *  产品标引属性列表查询
     */
    winAttrTabVal : Array<object>;
    winAttrPimVal : Array<object>;
    getReferenceProductIndexingMetaList(){
      let data = this._pimData();
      this.request.postRequest(this.server.baseUrl +"Service/IdxProduct/getProductIndexingMetaList",data).then((res:any) => {
        if (res.result_code === '0000') {
          this.winAttrPimVal = res.result;
          this.getReferenceMetaDataTemplateAttrList();
        }
      })
      .catch((err: any)=>{
        this.hintsService.messages("error","error");
        return;
      });
    }

    /**
   * 模板属性列表
   */
  getReferenceMetaDataTemplateAttrList(){
    let data = this._tableData();
    this.request.postRequest(this.server.baseUrl +"Service/Config/getMetaDataTemplateAttrList",data).then((res:any) => {
      if (res.result_code === '0000') {
        this.winAttrTabVal = res.result;
        if(this.winAttrTabVal && this.winAttrPimVal){
          this.winAttrTabVal = this.getAttrValue(this.winAttrTabVal,this.winAttrPimVal);
        }
      }

      
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }
  //获取属性的值
  getAttrValue(tempVal,pimVal){

    let i = 0;
    for (let temp of tempVal) {
      for (let pim of pimVal) {
          if(temp.metaId == pim.metaId){
            tempVal[i]['pimId'] = pim.id;
            tempVal[i]['metaValue'] = pim.metaValue;
          }
      }
      i++;
    }

    return tempVal;
  }

  //查询参数
  private _tableData(){
    return {
      token         : internal.retrieval.token,
      pageNo        : 1,
      pageSize      : 30,
      status        : '0',
      templateId    : this.internalParam.templateId,
    }
  }

   //查询参数
   private _pimData(){
    return {
      token         : internal.retrieval.token,
      pageNo        : 1,
      pageSize      : 30,
      productId     : this.productId,
      taskId        : this.taskId,
      templateId    : this.internalParam.templateId,
      themeId       : this.themeId,
      queryCriteria : ''
    }
  }

  win_hide_show(type:any){
    this.winTimeAttr = false;
    this.winAttr = false;
    if(type == 1){
      $("#myWinTxtTab li:first a").attr('class','active show');
    }
    $("#win_tab_attribute a").attr('class','');
    $("#win_tab_time_attribute a").attr('class','');
    $("#Wintab11").show();
    $("#Wintab22").hide();
    $("#Wintab33").hide();
  }

  //验证是否是时间类型
  _isTime(inputType:string){
    let typeVal = '';
    if(inputType == 'year' || inputType == 'yearmonth' || inputType == 'date' || inputType == 'datetime'){
      typeVal = 'AD';//公元
    }else if(inputType == 'bcyear' || inputType == 'bcyearmonth' || inputType == 'bcdate' || inputType == 'bcdatetime'){
      typeVal = 'BC';//公元前
    }else{
      typeVal = 'OTHER';//其他
    }
    return typeVal;
  }

  //修改时间类型值的格式
  _isTimeValue(metaValue,inputType:string){
    if(metaValue){
      //年
      if(inputType == "year" || inputType == "bcyear"){
        metaValue = metaValue + '年';
      }
      //年月
      if(inputType == "yearmonth" || inputType == "bcyearmonth"){
        let val = metaValue.split('-');
        let ymVal0 = val[0]?val[0]:'0000';
        let ymVal1 = val[1]?val[1]:'00';
        metaValue = ymVal0 + '年' + ymVal1 + '月';
      }
      //年月日
      if(inputType == "date" || inputType == "bcdate"){
        let val = metaValue.split('-');
        let dateVal0 = val[0]?val[0]:'0000';
        let dateVal1 = val[1]?val[1]:'00';
        let dateVal2 = val[2]?val[2]:'00';
        metaValue = dateVal0 + '年' + dateVal1 + '月' + dateVal2 + '日';
      }
      //年月日-时分秒
      if(inputType == "datetime" || inputType == "bcdatetime"){
        let arr = metaValue.split(' ');
        
        if(arr[0]){
          let valYMD = arr[0].split('-');
          let valYMD0 = valYMD[0]?valYMD[0]:'0000';
          let valYMD1 = valYMD[1]?valYMD[1]:'00';
          let valYMD2 = valYMD[2]?valYMD[2]:'00';
          metaValue = valYMD0 + '年' + valYMD1 + '月' + valYMD2 + '日 ';
        }
        if(arr[1]){
          let valTMS = arr[1].split(':');
          let valTMS0 = valTMS[0]?valTMS[0]:'00';
          let valTMS1 = valTMS[1]?valTMS[1]:'00';
          let valTMS2 = valTMS[2]?valTMS[2]:'00';
          if(metaValue){
            metaValue = metaValue + valTMS0 + '时' + valTMS1 + '分' + valTMS2 + '秒';
          }
        }
        
      }

      let str = '';
        if(this._isTime(inputType) == 'AD'){
          str = '公元 ';
        }else if(this._isTime(inputType) == 'BC'){
          str = '公元前 ';
        }
        metaValue = str + metaValue;
    }
    
    return metaValue;
  }

}
